package cn.wsalix.sys.service.impl;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.service.impl.CommonServiceImpl;
import cn.wsalix.sys.entity.DailyRecord;
import cn.wsalix.sys.form.DailyRecordForm;
import cn.wsalix.sys.repository.DailyRecordRepository;
import cn.wsalix.sys.service.DailyRecordService;
import cn.anlaser.utils.DateUtils;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;

@Service("dailyRecordService")
public class DailyRecordServiceImpl extends
		CommonServiceImpl<DailyRecordForm, DailyRecordRepository, DailyRecord>
		implements DailyRecordService {
	@Autowired
	private DailyRecordRepository dailyRecordRepository;

	@Override
	public String module() {
		return "/sys/daily_record";
	}

	@Override
	public DailyRecordRepository getRepository() {
		return dailyRecordRepository;
	}

	@Override
	public Class<DailyRecord> getEntityClazz() {
		return DailyRecord.class;
	}

	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	public Map<String, SearchFilter> buildByForm(DailyRecordForm form) {
		Map<String, SearchFilter> filters = buildFilter();
		if (form.getDaily() != null && !form.getDaily().equals("")) {
			filters.put("daily",
					new SearchFilter("daily", Operator.EQ, form.getDaily()));
			// dateFormat.format(form.getDaily())));org.springframework.dao.InvalidDataAccessApiUsageException:
			// Parameter value [2016-08-21] did not match expected type
			// [java.util.Date (n/a)]; nested exception is
			// java.lang.IllegalArgumentException: Parameter value [2016-08-21]
			// did not match expected type [java.util.Date (n/a)]
			// "DATE_FORMAT(" + form.getDaily() + ",'%Y-%m-%d')"));
		}// DATE_FORMAT(daily,'%Y-%m-%d')
		return filters;
	}

	@Transactional
	@Override
	public DailyRecord newDay() {
		DailyRecordForm dailyRecordForm = new DailyRecordForm();
		dailyRecordForm.setDaily(DateUtils.getNowDate());
		List<DailyRecord> dailyRecords = findByForm(dailyRecordForm);
		if (dailyRecords.size() >= 1) {
			return dailyRecords.get(0);
		} else {
			DailyRecord dailyRecord = new DailyRecord();
			dailyRecord.setDaily(DateUtils.getNowDate());
			
			return dailyRecord;
		}

	}

}
